<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择群" prop="groupId">
        <el-col :span="15">
          <el-form-item prop="groupId">
            <el-select v-model="queryParams.groupId" placeholder="请选择"
                       style="width: 180px" @change="handleQuery">
              <el-option
                  v-for="dict in userGroups"
                  :key="dict.id"
                  :label="dict.groupName"
                  :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="时间">
        <el-col :span="15">
          <el-date-picker
              v-model="queryParams.findTime"
              type="daterange"
              @change="handleQuery"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
          />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['group:participator:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['group:participator:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['group:participator:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['group:participator:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="participatorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="时间" align="center" prop="createTime" width="120px">
        <template #default="scope">
          {{format(scope.row.createTime, 'yyyy-MM-dd')}}
        </template>
      </el-table-column>
      <el-table-column v-if="!activityId &&!queryParams.groupId" label="群名称" align="center" prop="groupName"/>
      <el-table-column label="活动文本内容" align="center" prop="txtContent"/>
      <el-table-column label="费用" align="center" prop="cost"/>
      <el-table-column label="是否免费" align="center" prop="feeCharge">
        <template #default="scope">
          <dict-tag :options="group_login_default" :value="scope.row.feeCharge"/>
        </template>
      </el-table-column>
      <el-table-column label="是否半程" align="center" prop="halfFlag">
        <template #default="scope">
          <dict-tag :options="group_login_default" :value="scope.row.halfFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="是否飞机" align="center" prop="onlySite">
        <template #default="scope">
          <dict-tag :options="group_login_default" :value="scope.row.onlySite"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortNum"/>
      <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
      <!--        <template #default="scope">-->
      <!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"-->
      <!--                     v-hasPermi="['group:participator:edit']">修改-->
      <!--          </el-button>-->
      <!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"-->
      <!--                     v-hasPermi="['group:participator:remove']">删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改活动参与者对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="participatorRef" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="选择群" prop="groupId" disabled="groupId.value?true:false">-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item  prop="groupId">-->
        <!--              <el-select v-model="form.groupId" placeholder="请选择" >-->
        <!--                <el-option-->
        <!--                    v-for="dict in userGroups"-->
        <!--                    :key="dict.id"-->
        <!--                    :label="dict.groupName"-->
        <!--                    :value="dict.id"-->
        <!--                ></el-option>-->
        <!--              </el-select>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-form-item>-->
        <el-form-item label="id" prop="activityId">
          <el-input v-model="form.activityId" placeholder="请输入id"/>
        </el-form-item>
        <el-form-item label="用户和群id" prop="userGroupRefId">
          <el-input v-model="form.userGroupRefId" placeholder="请输入用户和群id"/>
        </el-form-item>
        <el-form-item label="活动文本内容">
          <editor v-model="form.txtContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="是否免费：0否，1是" prop="feeCharge">
          <el-input v-model="form.feeCharge" placeholder="请输入是否免费：0否，1是"/>
        </el-form-item>
        <el-form-item label="是否半程：0否，1是" prop="halfFlag">
          <el-input v-model="form.halfFlag" placeholder="请输入是否半程：0否，1是"/>
        </el-form-item>
        <el-form-item label="是否飞机：0否，1是" prop="onlySite">
          <el-input v-model="form.onlySite" placeholder="请输入是否飞机：0否，1是"/>
        </el-form-item>
        <el-form-item label="费用" prop="cost">
          <el-input v-model="form.cost" placeholder="请输入费用"/>
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input v-model="form.sortNum" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="是否删除" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入是否删除"/>
        </el-form-item>
        <el-form-item label="租户编号" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户编号"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Participator">
import * as participatorApi from '@/api/group/participator.js';
import * as groupServer from "@/api/group/group.js";
import {AES_Decrypt} from "@/utils/jsencrypt.js";
import {format} from "date-fns";

const {proxy} = getCurrentInstance();

const {
  group_login_default,
} = proxy.useDict( "group_login_default");
const participatorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const route = useRoute();
const activityId = ref(Number(AES_Decrypt(route.query.activityId)) === 0 ? undefined : Number(AES_Decrypt(route.query.activityId)));
const groupId = ref(Number(AES_Decrypt(route.query.groupId)) === 0 ? undefined : Number(AES_Decrypt(route.query.groupId)));
const userGroupRefId = ref(Number(AES_Decrypt(route.query.userGroupRefId)) === 0 ? undefined : Number(AES_Decrypt(route.query.userGroupRefId)));
const userGroups = ref([])
const resetFlag = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    orderByColumn: 'create_time desc,sortNum',
    isAsc: 'asc',
    groupId: groupId.value,
    startTime: null,
    findTime: null,
    endTime: null,
    orderByType: 4,
    orderByTypeDesc: 2,
    pageNum: 1,
    pageSize: 50,
    activityId: activityId.value,
    userGroupRefId: userGroupRefId.value,
    txtContent: null,
    feeCharge: null,
    halfFlag: null,
    onlySite: null,
    cost: null,
    sortNum: null,
    tenantId: null,
  },
  rules: {
    activityId: [
      {required: true, message: "id不能为空", trigger: "blur"}
    ],
    txtContent: [
      {required: true, message: "活动文本内容不能为空", trigger: "blur"}
    ],
    feeCharge: [
      {required: true, message: "是否免费：0否，1是不能为空", trigger: "blur"}
    ],
    halfFlag: [
      {required: true, message: "是否半程：0否，1是不能为空", trigger: "blur"}
    ],
    onlySite: [
      {required: true, message: "是否飞机：0否，1是不能为空", trigger: "blur"}
    ],
    cost: [
      {required: true, message: "费用不能为空", trigger: "blur"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: true, message: "更新时间不能为空", trigger: "blur"}
    ],
    deleted: [
      {required: true, message: "是否删除不能为空", trigger: "blur"}
    ],
    tenantId: [
      {required: true, message: "租户编号不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const start = (() => {
  return new Promise(resolve => {
    groupServer.callFindList(null).then(res => {
      userGroups.value = res.data
      if (!groupId.value  && !resetFlag.value ) {
        userGroups.value.forEach(item => {
          if (item.loginDefault === 1) {
            groupId.value = item.id
            queryParams.value.groupId = item.id
          }
        })
      }
      if (!groupId.value && !resetFlag.value) {
        groupId.value = userGroups.value[0].id
        queryParams.value.groupId = userGroups.value[0].id
      }
    }).then(() => {
      // //console.log("start",currentAdmin.value)
      resolve()
    })
  })
})

/** 查询活动参与者列表 */
function getList() {
  loading.value = true;
  start().then(() => {
    if (queryParams.value.findTime) {
      queryParams.value.endTime = queryParams.value.findTime[1]
      queryParams.value.startTime = queryParams.value.findTime[0]
    }
    //console.log("splice", queryParams.value);
    participatorApi.listParticipator(queryParams.value).then(response => {
      participatorList.value = response.data.list;
      total.value = response.data.total;
      loading.value = false;
    });
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单清空
function reset() {
  form.value = {
    startTime: null,
    findTime: null,
    endTime: null,
    id: null,
    activityId: activityId.value ? activityId.value : null,
    userGroupRefId: userGroupRefId.value ? userGroupRefId.value : null,
    txtContent: null,
    feeCharge: null,
    halfFlag: null,
    onlySite: null,
    cost: null,
    sortNum: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    tenantId: null,
    remark: null
  };
  proxy.resetForm("participatorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 清空按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.groupId = undefined;
  form.value.groupId = undefined;
  groupId.value = null
  activityId.value = null
  queryParams.value.activityId = undefined;
  form.value.activityId = undefined;
  resetFlag.value = true;
  queryParams.value.startTime = null;
  queryParams.value.findTime = null;
  queryParams.value.endTime = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加活动参与者";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]
  participatorApi.getParticipator({id: _id}).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改活动参与者";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["participatorRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        participatorApi.updateParticipator(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        participatorApi.addParticipator(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id ? [row.id] : ids.value;

  proxy.$modal.confirm('是否确认删除活动参与者编号为"' + _ids + '"的数据项？').then(function () {
    return participatorApi.delParticipator({delIds: _ids});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('group/participator/export', {
    ...queryParams.value
  }, `participator_${new Date().getTime()}.xlsx`)
}

getList();
</script>
